package com.macro.mall.controller;

import com.alibaba.fastjson.JSON;
import com.macro.mall.bean.vo.*;
import com.macro.mall.biz.IdGeneratorBiz;
import com.macro.mall.constant.CommonUtil;
import com.macro.mall.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Api(tags = "ID生成接口",value = "ID生成接口")
@RestController
@RequestMapping("/idGenerator")
public class IdGeneratorController {

    private static final Logger logger = LoggerFactory.getLogger(IdGeneratorController.class);

    @Autowired
    private IdGeneratorBiz idGeneratorBiz;

    @ApiOperation(value = "ID生成",notes = "ID生成规则: nowDate(14)+dataFlag(2)+busiCode(4)+serverSeq(2)+flowSeq(10)",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/getId",method= RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public IdGeneratorResVO getId(@ApiParam(value = "ID生成请求报文",required = true) @RequestBody IdGeneratorVO idGeneratorVO){
        logger.info("ID生成请求报文[idGeneratorVO={}]：",JSON.toJSONString(idGeneratorVO));
        IdGeneratorResVO respVo = new IdGeneratorResVO();
        try {
            Long getUserId = idGeneratorVO.getUserId();
            if(getUserId==null){
                throw new BusinessException("userId is not null");
            }
            String busiCode = idGeneratorVO.getBusiCode();
            if(StringUtils.isEmpty(busiCode)){
                throw new BusinessException("busiCode is not null");
            }else{
                Pattern pattern = Pattern.compile("^[0-9]*$");//校验纯数字
                Matcher match = pattern.matcher(busiCode);
                if(!match.matches()){
                    throw new BusinessException("busiCode is not number");
                }
            }
            respVo.setResult(idGeneratorBiz.getIdGenerator(getUserId,busiCode));
            logger.info("ID生成响应报文[resposeVO={}]：", JSON.toJSONString(respVo));
            return respVo;
        } catch (Exception e) {
            respVo.setRespCode("9999");
            respVo.setRespDesc(e.getMessage());
            logger.error("ID生成响应异常报文[resposeVO={}]：",JSON.toJSONString(respVo));
            return respVo;
        }

    }

    @ApiOperation(value = "订单ID生成器",notes = "订单ID生成器生成规则: serverSeq(1)+dataFlag(1)+nowDate(12)+flowSeq(6) orderType: 0-普通订单、1-5G订单、2-权益订单(积分商城)、3-权益订单(集运平台)",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/getOrderId",method= RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public IdGeneratorResVO getOrderId(@ApiParam(value = "订单ID生成请求报文",required = true) @RequestBody OrderIdGeneratorVO orderIdGeneratorVO){
        logger.info("订单ID生成请求报文[orderIdGeneratorVO={}]：",JSON.toJSONString(orderIdGeneratorVO));
        IdGeneratorResVO respVo = new IdGeneratorResVO();
        try {
            Long getUserId = orderIdGeneratorVO.getUserId();
            if(getUserId==null){
                throw new BusinessException("userId is not null");
            }
            String orderType = orderIdGeneratorVO.getOrderType();
            if(StringUtils.isEmpty(orderType)){
                orderType = "0";
            }else{
                if(CommonUtil.orderTypeMap.get(orderType)==null){
                    throw new BusinessException("orderType is not exist");
                }
            }
            respVo.setResult(idGeneratorBiz.getOrderIdGenerator(getUserId,orderType));
            logger.info("ID生成响应报文[resposeVO={}]：", JSON.toJSONString(respVo));
            return respVo;
        } catch (Exception e) {
            respVo.setRespCode("9999");
            respVo.setRespDesc(e.getMessage());
            logger.error("ID生成响应异常报文[resposeVO={}]：",JSON.toJSONString(respVo));
            return respVo;
        }

    }

    @ApiOperation(value = "porderId生成器",notes = "porderId生成器生成规则: 实物类P开头， 虚拟类V开头，异常订单R开头，后面14位格式： yymmdd+8位数字(自增序列)",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/getPorderId",method= RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public IdGeneratorResVO getPorderId(@ApiParam(value = "订单ID生成请求报文",required = true) @RequestBody PorderIdGeneratorVO porderIdGeneratorVO){
        logger.info("porderId生成请求报文[porderIdGeneratorVO={}]：",JSON.toJSONString(porderIdGeneratorVO));
        IdGeneratorResVO respVo = new IdGeneratorResVO();
        try {
            String porderType = porderIdGeneratorVO.getPorderType();
            if(porderType==null){
                throw new BusinessException("porderType is not null");
            }
            respVo.setResult(idGeneratorBiz.getPorderIdGenerator(porderType));
            logger.info("porderId生成响应报文[resposeVO={}]：", JSON.toJSONString(respVo));
            return respVo;
        } catch (Exception e) {
            respVo.setRespCode("9999");
            respVo.setRespDesc(e.getMessage());
            logger.error("porderId生成响应异常报文[resposeVO={}]：",JSON.toJSONString(respVo));
            return respVo;
        }

    }

    /**
     * 根据订单id查询 orderId的组合信息
     */
    @ApiOperation(value = "获取orderId拼接信息",notes = "根据订单id查询 orderId的组合信息",consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = "/getOrderIdInfo",method= RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<OrderIdInfoRspVO> getOrderIdInfo(@ApiParam(value = "订单ID生成请求报文",required = true) @RequestBody OrderIdInfoReqVO orderIdInfoReqVO){
        logger.info("获取orderId拼接信息请求报文[orderIdInfoReqVO={}]：",JSON.toJSONString(orderIdInfoReqVO));
        OrderIdInfoRspVO vo = new OrderIdInfoRspVO();
        try {
            String orderId = orderIdInfoReqVO.getOrderId();
            if((orderId.length() != 20 || !isNumeric(orderId))){
                throw new BusinessException("订单为20位长度的纯数字");
            }
            OrderIdInfoRspVO.OrderIdInfo orderIdInfo = vo.new OrderIdInfo();
            orderIdInfo.setServerSeq(orderId.substring(0,1));
            orderIdInfo.setDataFlag(orderId.substring(1,2));
            orderIdInfo.setNowDate(orderId.substring(2,14));
            orderIdInfo.setFlowSeq(orderId.substring(14,20));
            if(orderIdInfo.getDataFlag().equals("6")){
                orderIdInfo.setOrderType(CommonUtil.OrderType.GOLD);
            }else if(orderIdInfo.getDataFlag().equals("7")){
                orderIdInfo.setOrderType(CommonUtil.OrderType.BENEFITS_JF);
            }else if(orderIdInfo.getDataFlag().equals("8")){
                orderIdInfo.setOrderType(CommonUtil.OrderType.BENEFITS_JY);
            }else {
                orderIdInfo.setOrderType(CommonUtil.OrderType.COMMON);
            }
            vo.setOrderIdInfo(orderIdInfo);
            logger.info("获取orderId拼接信息响应报文[resposeVO={}]：", JSON.toJSONString(vo));
            return new ResponseEntity<>(vo, HttpStatus.OK);
        } catch (Exception e) {
            vo.setRespCode("9999");
            vo.setRespDesc(e.getMessage());
            logger.error("获取orderId拼接信息响应异常报文[resposeVO={}]：",JSON.toJSONString(vo));
            return new ResponseEntity<>(vo, HttpStatus.OK);
        }

    }

    private boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("^[0-9]*$");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }

}
